Page({
  data: {
    avatarUrl: '',
    nickName: '',
    gender: '',
    account: '',
    canSave: false,
    originalUserInfo: null
  },
  
  onLoad() {
    // 加载当前用户信息
    const app = getApp();
    if (!app) {
      console.error('【editProfile.js】应用实例不存在');
      wx.showToast({ title: '应用初始化失败', icon: 'none' });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    const userInfo = app.globalData?.userInfo;
    if (userInfo) {
      // 验证账号格式
      const accountValid = userInfo.account && userInfo.account.length >= 3;
      
      // 深拷贝原始用户信息，避免引用问题
      const originalUserInfo = JSON.parse(JSON.stringify(userInfo));
      
      // 确保原始用户信息也包含默认的gender值
      if (!originalUserInfo.gender) {
        originalUserInfo.gender = 'male';
      }
      
      this.setData({
        avatarUrl: userInfo.avatarUrl || '../../images/default_avatar.png',
        nickName: userInfo.nickName || '',
        gender: userInfo.gender || 'male',
        account: userInfo.account || '',
        accountValid: accountValid,
        originalUserInfo: originalUserInfo
      }, this.checkCanSave);
      console.log('【editProfile.js】用户信息加载成功:', userInfo);
      console.log('【editProfile.js】原始用户信息:', originalUserInfo);
    } else {
      // 用户信息不存在，返回上一页
      console.log('【editProfile.js】用户信息不存在，返回上一页');
      wx.showToast({ 
        title: '用户信息不存在', 
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    }
  },
  
  onChooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        console.log('【editProfile.js】选择头像成功:', res.tempFilePaths[0]);
        this.setData({ avatarUrl: res.tempFilePaths[0] }, () => {
          console.log('【editProfile.js】头像更新后检查保存状态');
          this.checkCanSave();
        });
      },
      fail: error => {
        console.error('【editProfile.js】选择头像失败:', error);
        wx.showToast({ title: '选择头像失败', icon: 'none' });
      }
    });
  },
  
  onNickNameInput(e) {
    const nickName = e.detail.value;
    console.log('【editProfile.js】昵称输入:', nickName);
    this.setData({ nickName }, () => {
      this.checkCanSave();
    });
  },
  
  onGenderChange(e) {
    const gender = e.detail.value;
    console.log('【editProfile.js】性别选择:', gender);
    this.setData({ gender }, () => {
      this.checkCanSave();
    });
  },
  
  onAccountInput(e) {
    const account = e.detail.value;
    const isValid = account.length >= 3;
    
    console.log('【editProfile.js】账号输入:', account, '是否有效:', isValid);
    
    this.setData({ 
      account: account,
      accountValid: isValid
    }, () => {
      this.checkCanSave();
    });
    
    if (account && !isValid) {
      wx.showToast({ title: '账号至少3位字符', icon: 'none' });
    }
  },
  
  checkCanSave() {
    const { nickName, gender, account, accountValid } = this.data;
    
    // 添加调试信息
    console.log('【editProfile.js】checkCanSave 检查:', {
      nickName: !!nickName,
      gender: !!gender,
      account: !!account,
      accountValid: accountValid,
      nickNameValue: nickName,
      genderValue: gender,
      accountValue: account
    });
    
    // 检查必填字段（不包含头像）
    const hasNickName = nickName && nickName.trim() !== '';
    const hasGender = gender && (gender === 'male' || gender === 'female');
    const hasAccount = account && account.trim() !== '';
    const isAccountValid = accountValid === true; // 明确检查boolean值
    
    const allFilled = hasNickName && hasGender && hasAccount && isAccountValid;
    
    console.log('【editProfile.js】字段检查结果:', {
      hasNickName,
      hasGender,
      hasAccount,
      isAccountValid,
      allFilled
    });
    
    this.setData({ canSave: allFilled });
  },
  
  onSave() {
    const { avatarUrl, nickName, gender, account, originalUserInfo } = this.data;
    
    if (!nickName || !gender || !account) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
    
    if (account.length < 3) {
      wx.showToast({ title: '账号至少3位字符', icon: 'none' });
      return;
    }
    
    // 更新用户信息
    const updatedUserInfo = {
      ...originalUserInfo,
      avatarUrl: avatarUrl || originalUserInfo.avatarUrl, // 如果没有新头像，使用原头像
      nickName,
      gender,
      account,
      updateTime: new Date().toISOString()
    };
    
    // 保存到本地存储
    wx.setStorageSync('userInfo', updatedUserInfo);
    
    // 更新全局用户信息
    const app = getApp();
    if (app) {
      app.globalData.userInfo = updatedUserInfo;
    }
    
    wx.showToast({ title: '保存成功', icon: 'success' });
    setTimeout(() => {
      // 固定返回到我的页面
      wx.switchTab({
        url: '/pages/me/me',
        success: () => {
          console.log('【editProfile.js】保存成功后返回到我的页面');
        },
        fail: () => {
          wx.navigateBack();
        }
      });
    }, 800);
  },
  
  onBack() {
    const { nickName, gender, account, originalUserInfo } = this.data;
    
    // 添加调试信息
    console.log('【editProfile.js】onBack 检查修改:', {
      current: { nickName, gender, account },
      original: { 
        nickName: originalUserInfo?.nickName, 
        gender: originalUserInfo?.gender, 
        account: originalUserInfo?.account 
      }
    });
    
    // 更严格的比较，处理undefined和null的情况，并去除空格
    const currentNickName = (nickName || '').trim();
    const originalNickName = (originalUserInfo?.nickName || '').trim();
    const currentGender = (gender || '').trim();
    const originalGender = (originalUserInfo?.gender || '').trim();
    const currentAccount = (account || '').trim();
    const originalAccount = (originalUserInfo?.account || '').trim();
    
    const hasChanges = 
      currentNickName !== originalNickName ||
      currentGender !== originalGender ||
      currentAccount !== originalAccount;
    
    console.log('【editProfile.js】详细比较:', {
      nickName: { current: currentNickName, original: originalNickName, equal: currentNickName === originalNickName },
      gender: { current: currentGender, original: originalGender, equal: currentGender === originalGender },
      account: { current: currentAccount, original: originalAccount, equal: currentAccount === originalAccount }
    });
    console.log('【editProfile.js】hasChanges:', hasChanges);
    
    if (hasChanges) {
      wx.showModal({
        title: '确认返回',
        content: '您已修改了信息但未保存，确定要返回吗？',
        confirmText: '确定返回',
        cancelText: '继续编辑',
        success: (res) => {
          if (res.confirm) {
            // 固定返回到我的页面
            wx.switchTab({
              url: '/pages/me/me',
              success: () => {
                console.log('【editProfile.js】返回到我的页面成功');
              },
              fail: () => {
                wx.navigateBack();
              }
            });
          }
        }
      });
    } else {
      // 固定返回到我的页面
      wx.switchTab({
        url: '/pages/me/me',
        success: () => {
          console.log('【editProfile.js】返回到我的页面成功');
        },
        fail: () => {
          wx.navigateBack();
        }
      });
    }
  }
}); 